package com.moblie.resources.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.moblie.frame.utils.ContextHolderUtils;
import com.moblie.frame.utils.Md5;
import com.moblie.resources.entity.Resources;
import com.moblie.resources.entity.SysUser;
import com.moblie.resources.service.SysUserService;

/**
 * 
 * @author <Auto generate>
 * @version 2015-05-21 23:16:41
 */
@Controller
public class LoginController {
	@Autowired
	private SysUserService sysUserService;

	@RequestMapping("/")
	public String home(Long id) {
		return "/login";
	}

	@ResponseBody
	@RequestMapping(value = "/login")
	public Object loginPost(SysUser sysUser, Model model) throws Exception {
		// type 类型用来标注会员类型,0表示普通会员
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			SysUser tempUser = sysUserService.selectSysUserByEntity(sysUser);
			if (tempUser == null) {
				map.put("error", "账号不存在!");
			} else {
				if (StringUtils.isEmpty(sysUser.getPassword())) {
					map.put("error", "请输入密码!");
				} else {
					String md5pwd = Md5.GetMD5Code(sysUser.getPassword());
					if (!md5pwd.equals(tempUser.getPassword())) {
						map.put("error", "您输入的密码不正确!");
					}
				}
			}
			if (map.isEmpty()) {
				// 初始化用户session
				sysUserService.initSysUserLogin(tempUser);
				map.put("status", 200);
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("error", "未知错误,请联系管理员.");
		}
		return map;
	}

	@RequestMapping(value = "/logout")
	public String logout(HttpServletRequest request) {
		HttpSession session = request.getSession(false);// 防止创建Session
		if (session != null) {
			session.removeAttribute("username");
			session.removeAttribute("name");
			session.removeAttribute("user");
			session.removeAttribute("roles");
			session.removeAttribute("resources");
		}
		return "redirect:/";
	}

	/**
	 * 主页
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/index")
	public String index(Model model) throws Exception {
		HttpSession session = ContextHolderUtils.getSession();
		if (session.getAttribute("user") == null) {
			return "redirect:/";
		}
		return "/index";
	}
	
	/**
	 * 首页
	 * @author liupf
	 * @param resource
	 * @return
	 */
	@RequestMapping("/home")
	public String list(Resources resource) {
		return "/home";
	}
}
